import axios from 'axios'

const request = axios.create({
  baseURL: '/api',  // 这里保持 /api，因为我们会在 vite.config.js 中配置代理
  timeout: 5000
})

request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('authToken')
    console.log('Request Interceptor - Token:', token)
    console.log('Request Interceptor - Original Headers:', config.headers)
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
      console.log('Request Interceptor - Modified Headers:', config.headers)
    } else {
      console.warn('No authToken found in localStorage')
    }
    return config
  }
)

request.interceptors.response.use(
  (response) => {
    if (response.config.responseType === 'blob') {
      return response
    }
    return response.data
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      // token失效，清除token并跳转到登录页
      localStorage.removeItem('authToken')
      window.location.href = '/me/login'
    }
    return Promise.reject(error)
  }
)

export default request